package dichotomyMethod;

import org.junit.Test;

/*
 *@description 寻找两个正序数组的中位数
 *@author hkfan
 *@version 1.0
 *@create 2025/5/15 15:33
*/
public class LeetCode_4 {

    @Test
    public void test(){
        System.out.println(findMedianSortedArrays(
                new int[]{1},
                new int[]{1}
        ));

    }

    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        if (nums1.length>nums2.length){
            return findMedianSortedArrays(nums2,nums1);
        }
        int l=0,r=nums1.length;
        while (l<=r){
            int i = (l+r)/2;
            int j = (nums1.length+nums2.length+1)/2-i;//左侧>=右侧
            int left_1=(i>0)?nums1[i-1]:Integer.MIN_VALUE;
            int right_1=(i< nums1.length)?nums1[i]:Integer.MAX_VALUE;
            int left_2=(j>0)?nums2[j-1]:Integer.MIN_VALUE;
            int right_2=(j< nums2.length)?nums2[j]:Integer.MAX_VALUE;
            if (left_1<=right_2 && left_2<=right_1){
                if ((nums1.length+nums2.length)%2==1){
                    return Math.max(left_1,left_2);
                }else {
                    return (Math.max(left_1,left_2)+Math.min(right_1,right_2))*1.0/2;
                }
            }else if (left_1>right_2){  //左移
                r=i-1;
            }else {
                l=i+1;
            }
        }
        return 1;
    }


}
